package com.wsoft.cms.manager;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wsoft.cms.entity.CmsAnnouncementSummaryEntity;
import com.wsoft.cms.enums.SummaryTypeEnum;
import com.wsoft.cms.mapper.CmsAnnouncementSummaryMapper;
import com.wsoft.constant.redis.RedisKeyConstant;
import com.wsoft.core.annotation.GetRedisCache;
import com.wsoft.core.service.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @Author z001
 * @Date 2024/11/27 10:42
 */
@Slf4j
@Service
public class CmsAnnouncementSummaryManager extends ServiceImpl<CmsAnnouncementSummaryMapper, CmsAnnouncementSummaryEntity> {

    @Resource
    private RedisService redisService;

    /**
     * 新增个数
     * @param annoId 文章id
     * @param type 类型
     * @param count 新增个数
     */
    public synchronized void addCount(Long annoId, String type,int count){
        CmsAnnouncementSummaryEntity summary = getById(annoId);
        if(summary == null){
            summary = new CmsAnnouncementSummaryEntity();
            summary.setAnnoId(annoId);
            summary.setCommentNum(0L);
            summary.setViewNum(0L);
            summary.setSignNum(0L);
            save(summary);
        }
        if(SummaryTypeEnum.VIEW.getType().equals(type)){
            summary.setViewNum(summary.getViewNum() + count);
        }else if(SummaryTypeEnum.COMMENT.getType().equals(type)){
            summary.setCommentNum(summary.getCommentNum() + count);
        }else if(SummaryTypeEnum.SIGN.getType().equals(type)){
            summary.setSignNum(summary.getSignNum() + count);
        }
        this.updateById(summary);
    }

    @Override
    public boolean updateById(CmsAnnouncementSummaryEntity summary){
        boolean b = super.updateById(summary);
        if(b){
            redisService.del(RedisKeyConstant.Cms.CMS_ANNO_SUMMARY_INFO + summary.getAnnoId());
        }
        return b;
    }

    /**
     * 根据id获取
     * @param annoId
     * @return
     */
    @GetRedisCache(type = RedisKeyConstant.Cms.CMS_ANNO_SUMMARY_INFO,
            expire_sec = RedisKeyConstant.Cms.EXPIRED,
            value = RedisKeyConstant.REDIS_SELF)
    public CmsAnnouncementSummaryEntity getById(Long annoId){
        QueryWrapper<CmsAnnouncementSummaryEntity> query = new QueryWrapper<>();
        query.lambda().eq(CmsAnnouncementSummaryEntity::getAnnoId,annoId);
        return getOne(query);
    }

}
